#include "stdafx.h"
#include "Xync.h"

#include <dbt.h>
#include <Shellapi.h>
#include <Shlwapi.h>
#include <Strsafe.h>

#include "Foxdev.h"
#include "Dialog.h"
#include "Notify.h"
#include "Setup.h"
#include "UpgraApp.h"

#pragma comment(lib,"Shlwapi.lib")

class Xync:public Dialog{
public:
	static void	run		(HINSTANCE,LPTSTR);

private:
	Xync(HINSTANCE instance):Dialog(instance,MAKEINTRESOURCE(IDD_ABOUTBOX),0){
		cursor=LoadCursor(0,IDC_ARROW);
		icon=LoadIcon(inst,MAKEINTRESOURCE(IDI_FOXYNC));
		menu=LoadMenu(inst,MAKEINTRESOURCE(IDC_FOXYNC));
		notify=new Notify(this,1,icon);
	};
	~Xync(){
		delete notify;
		end(0);
	}

	static TCHAR	appName[];
	static void	browse		(void);
	static void	uniqueness	(void);

	virtual LRESULT	wmCommand		(WPARAM,LPARAM);
	virtual LRESULT	wmDeviceChange	(WPARAM,LPARAM);
	virtual void	wmNotifyIcon	(WPARAM,LPARAM);
	virtual void	wmUpgrade		(WPARAM,LPARAM);

	Notify	*notify;
	HCURSOR	cursor;
	HICON	icon;
	HMENU	menu;
};

TCHAR	Xync::appName[]=L"XYNC";

void Xync::browse(void){
	ShellExecute(0,L"open",L"http://www.douban.com/group/445833/",0,0,SW_SHOW);
}
void Xync::run(HINSTANCE instance,LPTSTR cmdLine){
	uniqueness();
	if(StrCmp(cmdLine,L"-nosetup"))
		Setup::on();
	Xync *d=new Xync(instance);
	Foxdev::openAll();
	UpgraApp::begin(d);
	d->messageLoop();
	UpgraApp::end();
	Foxdev::closeAll();
	delete d;
}
void Xync::uniqueness(void){
	HANDLE mutex=CreateMutex(NULL,FALSE,appName);
	if(mutex!=NULL){
		if(GetLastError()!=ERROR_ALREADY_EXISTS)
			return;
	}
	ExitProcess(0);
}
LRESULT Xync::wmCommand(WPARAM wparam,LPARAM lparam){
	switch(LOWORD(wparam)){
	case IDOK:
	case IDCANCEL:
		hide();
		break;
	case IDM_ABOUT:
		show();
		break;
	case IDM_EXIT:
		Setup::off();
		PostQuitMessage(0);
		break;
	case IDM_WEBSITE:
		browse();
		break;
	default:
		return FALSE;
	}
	return TRUE;
}
LRESULT Xync::wmDeviceChange(WPARAM wparam,LPARAM lparam){
	switch(wparam){
	case DBT_DEVICEREMOVECOMPLETE:
		Foxdev::closeAll();
		break;
	case DBT_DEVNODES_CHANGED:
		Foxdev::closeAll();
	case DBT_DEVICEARRIVAL:
		Foxdev::openAll();
		break;
	default:
		return 1;
	}
	return 0;
}
void Xync::wmNotifyIcon(WPARAM id,LPARAM mouseMessage){
	SetCursor(cursor);
	switch(mouseMessage){
	case WM_LBUTTONDBLCLK:
		browse();
		break;
	case WM_RBUTTONUP:
		POINT p;
		GetCursorPos(&p);
		TrackPopupMenu(GetSubMenu(menu,0),TPM_LEFTALIGN|TPM_TOPALIGN,
			p.x,p.y,0,hwnd,NULL);
		break;
	}
}
void Xync::wmUpgrade(WPARAM id,LPARAM mouseMessage){
	//setup(0);
	//PostQuitMessage(0);
}

int APIENTRY _tWinMain(HINSTANCE instance,HINSTANCE prevInstance,
	LPTSTR cmdLine,int cmdShow){
	Xync::run(instance,cmdLine);
	return 0;
}